package com.jingfang.cloud.initialize;

import cn.hutool.core.swing.DesktopUtil;
import cn.hutool.core.util.RuntimeUtil;
import cn.hutool.core.util.ZipUtil;
import com.jingfang.cloud.MzContext;
import com.jingfang.cloud.MzPrefs;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.quickswing.ui.app.QSWidget;

import java.io.File;

@Slf4j
public class MzAppInitializer {
    private final QSWidget<MzPrefs> application;
    private final MzContext context;
    private final MzPrefs prefs;

    public MzAppInitializer(QSWidget<MzPrefs> application) {
        this.application = application;
        this.context = (MzContext) application.getContext();
        this.prefs = application.getPrefs();
    }

    public static MzAppInitializer create(QSWidget<MzPrefs> application) {
        return new MzAppInitializer(application);
    }

    @Data
    @AllArgsConstructor
    public static class UsbDriverInstallInfo {
        private int code;
        private File file;
    }

    public void initialize() {
        context.taskExecute(() -> {
            log.info("初始化程序...");
            if (prefs.getUsbDriverInstalled()) {
                log.info("检测到串口驱动程序已安装。");
                return new UsbDriverInstallInfo(1, null);
            } else {
                log.info("检测到串口驱动程序未安装。");
                String currentZip = System.getProperty("user.dir") + File.separator + "STM32USB.zip";
                String tmpZip = prefs.buildTmpFile("STM32USB");
                File unzip = ZipUtil.unzip(currentZip, tmpZip);
                log.info("解压驱动文件到：{}", unzip.getAbsolutePath());
                if (unzip.exists()) {
                    Process exec = RuntimeUtil.exec(unzip.getAbsolutePath() + File.separator + "VCP_V1.4.0_Setup.exe");
                    int i = exec.waitFor();
                    return new UsbDriverInstallInfo(i, unzip);
                }
                return new UsbDriverInstallInfo(-1, unzip);
            }
        }, (result, exception) -> {
            if (exception != null) {
                application.displayException("失败", exception);
                DesktopUtil.open(result.getFile());
            } else {
                if (result.getCode() == 0) {
                    prefs.setUsbDriverInstalled(true);
                    application.displayMessage("成功", "USB串口驱动安装成功！");
                }
                if (result.getCode() == -1) {
                    application.displayMessage("失败", "USB串口驱动安装失败,请手动安装.");
                    DesktopUtil.open(result.getFile());
                }
            }
        });

    }
}
